package com.xhl.doeverything.rabbitmq.service;

import cn.hutool.json.JSONUtil;
import com.rabbitmq.client.Channel;
import com.xhl.doeverything.po.User;
import com.xhl.doeverything.rabbitmq.constant.QueueConstant;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.support.AmqpHeaders;
import org.springframework.messaging.handler.annotation.Header;
import org.springframework.stereotype.Component;

import java.io.IOException;

/**
 * @author xionghuilong
 * @description: MQ消息接收
 * @date 2022/1/17 13:53
 */
@Slf4j
@Component
public class MessageReciever {

    @RabbitListener(queues = QueueConstant.USER_QUEUE, ackMode = "MANUAL")
    public  void processMessage(String eventStr, Channel channel, @Header(AmqpHeaders.DELIVERY_TAG) long deliveryTag) throws IOException, InterruptedException {

        Thread.sleep(1000l);
        log.info("1业务处理完毕。。。");

        User user = JSONUtil.toBean(eventStr, User.class);

        // 手动ack
        channel.basicAck(deliveryTag, true);

    }

    @RabbitListener(queues = QueueConstant.USER_QUEUE, ackMode = "MANUAL")
    public  void processMessage2(String eventStr, Channel channel, @Header(AmqpHeaders.DELIVERY_TAG) long deliveryTag) throws InterruptedException, IOException {

        channel.basicQos(1);
        Thread.sleep(2000l);
        log.info("2业务处理完毕。。。");

        User user = JSONUtil.toBean(eventStr, User.class);

        // 手动ack
        try {
            channel.basicAck(deliveryTag, true);
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
}
